package at.fhj.mobsecdev.cookit.webrequests;

import java.io.InputStream;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

/**
 * Downloads an image from the internet and displays it in an imageView
 */
public class GetImageWebCall extends AsyncTask<String, Void, Bitmap> {
	private ImageView imageView;
	
	public GetImageWebCall(ImageView imageView)
	{
		this.imageView = imageView;
	}

	
	/**
	 * param 0 = url
	 * param 1 = flag that indicates, if only the thumbnail should be loaded
	 */
	@Override
	protected Bitmap doInBackground(String... params) {
		String imageFileName = params[0];
		Boolean loadThumbnail = Boolean.valueOf(params[1]);
		
		String url = WebServiceUrls.IMAGE_URL;
		if(loadThumbnail)
		{
			url += WebServiceUrls.THUMBNAIL_PREFIX;
		}
		url += imageFileName;
		
        Bitmap image = null;
        try {
            InputStream in = new URL(url).openStream();
            image = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Could not load image with the following URL: " + url, e.getMessage());
            e.printStackTrace();
        }
		
		return image;
	}
	
	/**
	 * Display image in imageView
	 */
	@Override
	protected void onPostExecute(Bitmap result) {
		super.onPostExecute(result);

		if(result != null)
		{
			imageView.setBackgroundColor(0); 
			imageView.setImageBitmap(result);
		}
		
	}
}